<?php
class AttrHelper {
	/**
	 * 模块名称，用于获取对应的值，比如：goods/article/...
	 * @var string
	 */
	var $model_name = '';
	
	/**
	 * 视图器
	 * @var Viewer
	 */
	var $viewer = null;
	
	/**
	 * forms的完整数据
	 * @var array
	 */
	var $forms = null;
	
	/**
	 * 当前显示语言，未指定或者网站未开启此语言时，使用LANGUAGE
	 * @var string
	 */
	var $lang = null;
	
	/**
	 * 具体实例ID
	 * @var string
	 */
	var $entity_id = null;
	
	/**
	 * 数据在文档内的路径(如果是内文档)
	 * @var string
	 */
	var $item_id = null;
	
	public function AttrHelper($configs){
		if(isset($configs['lang'])){
			if(Lang::is_site_lang($configs['lang'])){
				$this->lang = $configs['lang'];
			}
		}
		if($this->lang===null || !Lang::is_lang($this->lang)){
			$this->lang = LANGUAGE;
		}
		
		$forms_mod = new FormsModel();
		if(isset($configs['id'])){
			$this->forms = $forms_mod->get_by_attrs(array('_id'=>$configs['id']));
			if($this->forms['site_id']!==SITE_ID){
				if($this->forms['owner']!='system'){
					//无权限使用别人的Forms
					echo '无权使用此表单：id=' . $configs['id'] . ',site_id='.$this->forms['site_id'].'！';
					$this->forms = null;
				}
			}
		}
		if(isset($configs['form_name'])){
			//使用名称去获取的时候，应该是系统的，或者自己的
			$this->forms = $forms_mod->get_by_attrs(array('name'=>$configs['form_name'], 'site_id'=>SITE_ID));
			if(empty($this->forms)){
				//尝试从系统中找
				$this->forms = $forms_mod->get_by_attrs(array('name'=>$configs['form_name'], 'owner'=>'system'));
			}
		}
		if(isset($configs['forms'])){
			$this->forms = &$configs['forms'];
		}
		
		if(!empty($this->forms)){
			$this->model_name = $this->forms['model'];
			$this->forms['is_mutil_lan'] = self::is_mutil_lan();
		}
		if(isset($_REQUEST['id'])){
			$configs['entity_id'] = $_REQUEST['id'];
		}
		if(isset($configs['entity_id'])){
			//指定了具体的实体
			$this->entity_id = trim($configs['entity_id']);
		}
		if(isset($configs['item_id'])){
			$this->item_id = $configs['item_id'];
		}
	}
	
	/**
	 * 格式化好用于列表显示的数据结构
	 */
	public function get_list_view_data(){
		if(!isset($this->forms['list_view'])){
			//如果没有设置有列表显示字段时
			return null;
		}
		$list_views =  $this->forms['list_view'];
		$attrs = self::get_form_items();
		$list_view_title = array();
		foreach($list_views as $list_field=>$sort_data){
			$list_view_title['title'][$list_field] = $attrs[$list_field][$this->lang]['name'];
		}
		return $list_view_title;
	}
	
	/**
	 * 保存Post进来的数据
	 * @param array $data
	 */
	public function save($data=null){
		if($data===null){
			$data = $this->get_post_data();
		}
		if(!$data['result']){
			//有错误发生
			return $data;
		}
		//处理保存逻辑
		$mod = m($this->model_name);
		$id = 0;
		if(isset($_REQUEST['id'])){
			$id = trim($_REQUEST['id']);
		}
		$data = $data['data'];
		if(isset($_REQUEST['column'])){
			//如果只是子项
			$column = trim($_REQUEST['column']);
			$item_id = 0;
			if(isset($_REQUEST['item_id'])){
				$item_id = trim($_REQUEST['item_id']);
			}
			if(empty($item_id)){
				$item_id = gen_guid();
			}
			$mod->update_by_key($id, array($column . '.' . $item_id=>$data));
			return array('result'=>true, 'info'=>Lang::get('success'));
		}else{
			if(empty($id)){
				//新增
				$mod->insert($data);
			}else{
				//修改
				$old_obj = $mod->get_by_key($id);
				$data = array_merge($old_obj, $data);
				$mod->update_by_key($id, $data);
			}
		}
		return array('result'=>true, 'info'=>Lang::get('success'), 'data'=>$data);
	}
	
	public function get_post_data(){
		$attr_items = $this->get_form_items();

		$mutil_lan = $this->forms['is_mutil_lan'];
		$data = array();
		foreach ($attr_items as $name=>$item){
			$item['id'] = $name;
			$attr_class_name = ucfirst($item['type']) . 'Attr';
			if($mutil_lan && $item['mutil_lan']){
				$attr_obj = new $attr_class_name($item, null, true);
			}else{
				$attr_obj = new $attr_class_name($item, null, false);
			}
			$attr_obj->forms = $this->forms;
			$attr_obj->get_post_val($data);
			if($attr_obj->error!==null){
				//有错误发生
				return array('result'=>false, 'info'=>$attr_obj->error);
			}
		}
		
		return array('result'=>true, 'info'=>'success', 'data'=>$data);
	}
	
	/**
	 * 获取表单项目
	 * @return Ambigous <multitype:, unknown_type>
	 */
	public function get_form_items() {
		$attr_items = array();
		if(isset($this->forms['items'])){
			$attr_items = $this->forms['items'];
		}
		if(isset($this->forms['attr_groups'])){
			//属性组
			$attr_groups = $this->forms['attr_groups'];
			
			$attr_group_ids = self::get_attr_group_ids($attr_groups);
			$attrs = self::get_attr_group_configs($attr_group_ids);
			$attr_items = array_merge($attr_items, $attrs);//合并属性组
		}
		return $attr_items;
	}

	
	public function get_html(){
		if(empty($this->forms))return '';
		$attr_items = self::get_form_items();
		
		$entity = null;
		if($this->entity_id!==null){
			$mod = m($this->model_name);
			$entity = $mod->get_by_key($this->entity_id, $this->item_id);
			if(!empty($entity)){
				if($this->item_id!==null){
					$keys = explode('.', $this->item_id);
					foreach ($keys as $key){
						$entity = $entity[$key];
					}
				}
				unset($entity['_id']);
				foreach ($entity as $attr_name => $attr_value){
					if(isset($attr_items[$attr_name])){
						//如果有值
						$attr_items[$attr_name]['value'] = $attr_value;
					}
				}
				$this->forms['entity_id'] = $this->entity_id;
			}
		}
			
		$ungroup_items = array();
		$mutil_lan = $this->forms['is_mutil_lan'];
		foreach ($this->forms['groups'] as $key=>&$group_item){
			//将attr_items封装进groups
			if(isset($group_item['items'])){
				$group_items = self::format_group_item($group_item['items'], $attr_items, $mutil_lan);
				$group_item['items'] = $group_items['items'];
				$group_item['mutil_lan_items'] = $group_items['mutil_lan_items'];
			}
		}
		sort_by_rank($this->forms['groups']);
		reset($this->forms);
		return self::get_forms_html($mutil_lan);
	}
	
	/**
	 * 判断当前Form是否支持多语言编辑（一般用于后台编辑），以Tab形式展示
	 * 返回true | false
	 */
	public function is_mutil_lan() {
		$mutil_lan = false;
		if(isset($this->forms['mutil_lan'])){
			$mutil_lan = $this->forms['mutil_lan'];
			if($mutil_lan === true){
				//检查本站是否支持多种语言
				global $site_info;//取得当前网站配置
				if(isset($site_info['langs'])){
					$mutil_lan = count($site_info['langs'])>1;
				}else{
					$mutil_lan = false;
				}
			}
		}
		return $mutil_lan;
	}
	
	public function format_forms_data(){
		//属性组ID
		$attr_confs = array();
		
		if(isset($this->forms['attr_groups'])){
			$attr_group_ids = $this->forms['attr_groups'];
			$gids = array_keys($attr_group_ids);
			$attr_confs = $this->get_attr_group_configs($gids);
		}
		if(isset($this->forms['items'])){
			foreach ($this->forms['items'] as $item_key=>$item){
				$item['forms_id'] = $this->forms['_id'];
				$attr_confs[$item_key] = $item;
			}
		}
		$types = AttrsModel::get_attr_types();
		$relation_mod = new RelationModel();
		$relations = $relation_mod->get_options();
		foreach ($attr_confs as &$attr){
			if(isset($types[$attr['type']])){
				$attr_type = $types[$attr['type']];
				$attr['type_name'] = $attr_type['name'];
				if(isset($attr['trait'])){
					if($attr['type'] == 'relation'){
						//关联属性
						$attr['relation_name'] = $relations[$attr['relation']];
					}
					$attr['trait_name'] = $attr_type['trait'][$attr['trait']];
				}
			}else{
				$attr['type_name'] = '未知';
			}
		}
		
		//封装到Groups
		if(isset($this->forms['groups'])){
			foreach ($this->forms['groups'] as $gid=>&$group){
				if(isset($group['items'])){
					foreach($group['items'] as $attr_id=>$item){
						if(isset($attr_confs[$attr_id])){
							$group['items'][$attr_id] = $attr_confs[$attr_id];
							$attr_confs[$attr_id]['grouped'] = true;
						}else{
							unset($group['items'][$attr_id]);
						}
					}
				}
			}
			sort_by_rank($this->forms['groups']);
		}
		
		//未分组属性
		$ungroup_items = array();
		foreach($attr_confs as $attr_id=>$attr_conf){
			if(isset($attr_conf['grouped'])){
				unset($attr_confs[$attr_id]);
			}else{
				$ungroup_items[$attr_id] = $attr_conf;
			}
		}
		return array(
			'forms' => $this->forms,
			'ungroups' => $ungroup_items,
		);
	}
	
	/**
	 * 重新格式化分组内的表单item
	 * 1. 将组内的表单项（自定义表单）按值由小到大排序
	 * 2. 将排序值换成表单属性配置（attrs）
	 * @param unknown_type $group_item
	 * @param unknown_type $attr_items
	 * @param unknown_type $mutil_lan 表单是否开启多语言编辑（一般应用于后台编辑框，以Tab形式展示）
	 */
	private function format_group_item($group_item, $attr_items, $mutil_lan=false){
		//重新排序
		asort($group_item);
		
		$items = array();
		foreach ($group_item as $name=>$sort_num){
			if(isset($attr_items[$name])){
				$attr_items[$name]['id'] = $name;
				$attr_items[$name]['rank'] = $sort_num;
				$items[] = $attr_items[$name];
			}
		}
		
		$mutil_lan_items = array();
		if($mutil_lan){
			//排序，将多语言的排在前面
			usort($items, 'sort_by_mutil_lan');
			foreach ($items as $id=>$item){
				if(isset($item['mutil_lan']) && $item['mutil_lan']){
					$mutil_lan_items[] = $item;
					unset($items[$id]);
				}
			}
			reset($items);
		}
		//重新排序
		sort_by_rank($items, false);
		sort_by_rank($mutil_lan_items, false);
		
		return array(
			'items' => $items,
			'mutil_lan_items' => $mutil_lan_items,
		);
	}
	
	public function show($attr_config){
		
	}
	
	/**
	 * 通过分类ID获取指定模块的扩展属性配置，如果指定了具体的实例，也将实例内的扩展属性值赋到配置内
	 * @param unknown_type $cate_ids 分类ID
	 * @param unknown_type $entity_id
	 */
	public function get_attr_configs($cate_ids, $entity_id=null){
		if(!empty($entity_id)){
			//获取值
			$entity_mod = &m($this->model_name);
			$attrs = $entity_mod->get_by_key($entity_id, LANGUAGE, LANGUAGE . '.attrs');
			$attr_values = null;
			if(!empty($attrs['attrs'])){
				$attr_values = $attrs['attrs'];
			}
		}
		
		//如果是字符串，则将其封装进数组内
		if(is_string($cate_ids)){
			$cate_ids = array($cate_ids);
		}
		
		//获取属性组
		$cate_mod = &m($this->model_name . '_cate');
		$attr_ids = $this->get_attr_from_cate($cate_ids, $cate_mod);
		$attr_group_ids = self::get_attr_group_ids($attr_ids);
		$attr_config = $this->get_attr_group_configs($attr_group_ids, $attr_values);
		return $attr_config;
	}
	
	private function get_attr_group_ids($attr_ids){
		$attr_group_ids = array();
		foreach ($attr_ids as $attr_group_id=>$rank){
			$attr_group_ids[] = $attr_group_id;
		}
		return $attr_group_ids;
	}
	
	/**
	 * 通过属性组ID获取各属性的配置，如果值的话，也把值赋进配置里面
	 * @param $attr_group_ids 属性组ID
	 */
	private function get_attr_group_configs($attr_group_ids){
		$attr_config = array();
		$attrs_mod = new AttrsModel();
		$attr_configs = $attrs_mod->find(array('site_id'=>SITE_ID, '_id'=>array('$in'=>$attr_group_ids)));
		
		foreach ($attr_configs as $config_id=>$config){
			if(empty($config['items']))continue;
			foreach ($config['items'] as $item_key => $items){
				//标识是从哪里来的
				$items['attr_id'] = $config_id;
				$attr_config[$item_key] = $items;
			}
		}
		return $attr_config;
	}
	
	/**
	 * 通过cate_id获取到所有的分类下的attr_ids，返回的id是属性组的ID
	 * @param unknown_type $cate_ids
	 * @param unknown_type $cate_mod
	 */
	private function get_attr_from_cate($cate_ids, $cate_mod) {
		$cates = $cate_mod->find(array('site_id'=>SITE_ID, '_id'=>array('$in'=>$cate_ids)), 'attrs');
		$attr_ids = array();
		foreach($cates as $cate){
			foreach($cate['attrs'] as $attr_id=>$attr_rank){
				$attr_ids[] = $attr_id;
			}
		}
		$attr_ids = array_unique($attr_ids);
		return $attr_ids;
	}
	
	private function get_forms_html($mutil_lan=false){
		//查找路径
		$template_file_names = array(
			'forms_' . $this->forms['name'] . '.' . TEMPLATE_TYPE,
			'forms.' . TEMPLATE_TYPE,
		);
		$template_path = false;
		foreach($template_file_names as $template_file_name){
			$template_path = self::get_template_path($template_file_name);
			if($template_path!==false)break;
		}
		if($template_path === false)return '未找到表单显示模板！';
	
		if($this->viewer === null){
			$this->viewer = Viewer::get_view();
		}
		$this->viewer->template_dir = $template_path;
		
		global $site_info;
		$langs = array();
		foreach($site_info['langs'] as $lang=>$is_default){
			$langs[$lang] = Lang::get_lan_name($lang);
		}
		$this->viewer->assign('site_langs', $langs);
		
		//初始化当前编辑语言
		$cur_lang = LANGUAGE;
		if(isset($_REQUEST['lang'])){
			$cur_lang = $_REQUEST['lang'];
			//判断是否合法
			if(!Lang::is_site_lang($cur_lang)){
				$cur_lang = LANGUAGE;
			}
		}
		$this->viewer->assign('cur_lang', $cur_lang);
		
		$this->viewer->assign('forms', $this->forms); //此处修改的话，应该相应修改模板及smarty扩展里面的值
		//$this->viewer->assign('mutil_lan', $mutil_lan);//定义是否开启多语言编辑（以Tab形式出现，一般用于管理后台）
		$html = $this->viewer->fetch($template_file_name);
		//抽取脚本
		
		
		$this->viewer->free();
		return $html;
	}
	
	private function get_template_path($template_name){
		$template_paths = array(
			ROOT_PATH . '/sites/main/' . MAIN_DOMAIN . '/template/data/forms/',	//用户私有模板
			ROOT_PATH . '/protected/includes/forms/template/'					//公共模板
		);
		foreach ($template_paths as $path){
			if(is_file($path . $template_name)){
				return $path;
			}
		}
		return false;
	}
	
	/**
	 * 格式化表单项目里面的值，比如表单类型、表单性状、表单关联类型名称等
	 * @param string $items
	 */
	public static function format_forms_items(&$items){
		global $types,$relations,$forms,$cate_types;
		
		if($types === null){
			$types = AttrsModel::get_attr_types();
		}
		
		if($relations === null){
			$relation_mod = new RelationModel();
			$relations = $relation_mod->get_options();
		}
		
		if($forms === null){
			$form_mod = new FormsModel();
			$forms = $form_mod->get_site_forms_option(array('site_id'=>SITE_ID));
		}
		
		if($cate_types === null){
			$cate_types = AttrsModel::get_cate_types();
		}
		
		foreach ($items as $name=>&$attr){
			if(isset($types[$attr['type']])){
				$attr_type = $types[$attr['type']];
				$attr['type_name'] = $attr_type['name'];
				if(isset($attr['trait'])){
					if($attr['type'] === 'relation'){
						//关联属性
						$attr['relation_name'] = $relations[$attr['relation']];
					}
					$attr['trait_name'] = $attr_type['trait'][$attr['trait']];
				}
				if(isset($attr['forms'])){
					$attr['relation_name'] = $forms[$attr['forms']];
				}elseif(isset($attr['cate'])){
					$attr['relation_name'] = $cate_types[$attr['cate']];
				}
			}else{
				$attr['type_name'] = '未知';
			}
		}
	}
}

/**
 * 根据语言排序，如果有mutil_lan属性且为true时，排到前面
 * @param unknown_type $r1
 * @param unknown_type $r2
 */
function sort_by_mutil_lan($r1, $r2){
	$l1 = false;
	if(isset($r1['mutil_lan'])){
		$l1 = $r1['mutil_lan'];
	}
	$l2 = false;
	if(isset($r2['mutil_lan'])){
		$l2 = $r2['mutil_lan'];
	}
	if($l1 && $l1)return 0;
	if($l1 && !$l2)return 1;
	if($l2 && !$l1)return -1;
	return 0;
}
?>